<?php

class FormFilter_DateTime extends FormFilter
{

  const EXACT = 'exact';

  const SINCE = 'since';

  const UNTIL = 'until';

  public $type = self::EXACT;

  public function injectQueryParams(&$params)
  {
    $key = $this->getForeignKey();
    $sk = $key . '_' . $this->type;
    $val = s::request()->get($sk);

    if (empty($val) && $this->required) {
      s::getInstance()->warnings('Select the ' . $this->getTitle());
      s::response()->redirect(array($this->redirect, $this->redirectParams));
    }

    if (! empty($val)) {
      $val = $this->formatDateTime($val);

      if (! empty($val) || $this->required) {
        switch ($this->type) {
          case self::SINCE:
            $params['where'][] = "$key >= :$sk";
            break;

          case self::UNTIL:
            $params['where'][] = "$key <= :$sk";
            break;

          default:
            $params['where'][] = "$key = :$sk";
        }

        $params['data'][$sk] = $val;
        $params['fields'][] = $key;
      }
    }
  }

  public function render()
  {
    $key = $this->getForeignKey();
    $sk = $key . '_' . $this->type;
    $val = s::request()->get($sk);

    if (! empty($val)) {
      $this->set('formatedValue', $val);
    }

    $this->set('filterName', $sk);

    return parent::render();
  }

  public function getTemplate()
  {
    /*$template = parent::getTemplate();

    if (empty($template)) {*/
      global $config;

      $template = $config['views_dir'] . '/form/form_filter_date_time_view.php';
    //}

    return $template;
  }

  protected function getFormated($value)
  {
    return date('d/m/Y H:i:s', strtotime($value));
  }

  protected function formatDateTime($date)
  {
    if (function_exists('date_parse_from_format')) {
      $dt = date_parse_from_format('d/m/Y H:i:s', $date);
      $dt = mktime($dt['hour'], $dt['minute'], $dt['second'], $dt['month'], $dt['day'], $dt['year']);

      $value = date('Y-m-d H:i:s', $dt);
    }
    elseif (function_exists('strptime')) {
      $dt = strptime($date, 'd/m/Y H:i:s');

      $value = date('Y-m-d H:i:s', $dt);
    }
    else {
      $parts = explode(' ', $date);

      $date = explode('/', $parts[0]);

      $d = $date[0];
      $m = $date[1];
      $Y = $date[2];

      $value = "$Y-$m-$d $parts[1]";
    }

    return $value;
  }

}

?>